package cn.hh.wechatkit.api.token;

import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import okhttp3.Headers;
import okhttp3.Response;
import java.io.IOException;
import com.alibaba.fastjson.JSON;
import cn.hhchat.kit.http.httpUtil;
import cn.hh.wechatkit.pojo.token.WxToken_AuthoAccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static cn.hh.wechatkit.helper.WxConst.AuthoAccessToken_Get_URL;
import static cn.hh.wechatkit.helper.WxConst.RefreshAuthoAccessToken_Get_URL;


/**
 * Created this one by HMH on 2«017/3/24.
 */
public class WxAPI_Autho_Access_token_Api {

    private static Logger logger = LoggerFactory.getLogger(WxAPI_Autho_Access_token_Api.class);

    /**
     * 获取AuthoAccessToken
     * @param appID appId
     * @param appsecret appsecret
     * @param CODE 认证返回的Code
     * @return AuthoAccessToken
     * @throws IOException io异常，一般为http发送出错
     * @throws Wx_Exception_InvalidJsonParse 无效的json异常
     * @throws Wx_Exception_InvalidResponse 无效的响应异常
     */
    public static WxToken_AuthoAccessToken getToken(String appID, String appsecret, String CODE) throws IOException, Wx_Exception_InvalidJsonParse, Wx_Exception_InvalidResponse {

        String url = AuthoAccessToken_Get_URL
                .replace("APPID", appID)
                .replace("SECRET", appsecret)
                .replace("CODE",CODE);
        Response response = httpUtil.get(url);
        return fillData(response);
    }

    /*
    刷新authoAccessToken，一般不用
     */

    public static WxToken_AuthoAccessToken refreshAuthoAccessToken(String APPID, String REFRESH_TOKEN) throws IOException, Wx_Exception_InvalidJsonParse, Wx_Exception_InvalidResponse {
        String url = RefreshAuthoAccessToken_Get_URL
                .replace("APPID", APPID)
                .replace("REFRESH_TOKEN", REFRESH_TOKEN);
        Response response = httpUtil.get(url);
        return fillData(response);
    }

    /*
    填充数据
     */

    private static WxToken_AuthoAccessToken fillData(Response response) throws Wx_Exception_InvalidJsonParse, Wx_Exception_InvalidResponse {
        if (response !=null ) {
            try {
                Headers headers = response.headers();
                String body = response.body().string();
                WxToken_AuthoAccessToken wxAuthoAccessToken = JSON.parseObject(body, WxToken_AuthoAccessToken.class);
                if (!wxAuthoAccessToken.hasError()) {
                    wxAuthoAccessToken.setScopes(wxAuthoAccessToken.getScope().split(","));
                    wxAuthoAccessToken.setExpires_time(wxAuthoAccessToken.getExpires_in() * 1000 + headers.getDate("date").getTime() - 1300000);
                }
                return wxAuthoAccessToken;
            } catch (IOException e) {
                logger.error("处理返回的AccessToken发生错误\n",e);
                throw new Wx_Exception_InvalidJsonParse("处理返回的AccessToken发生错误\n", e);
            }
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");

    }
}
